package com.example.universitylibraryback.controller;

import com.example.universitylibraryback.entity.Reader;
import com.example.universitylibraryback.service.ReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

import com.example.universitylibraryback.dto.ReaderDTO;
import com.example.universitylibraryback.dto.ResultDTO;
import org.springframework.beans.BeanUtils;
import java.util.stream.Collectors;

@Tag(name = "读者管理", description = "读者的增删改查等操作")
@RestController
@RequestMapping("/api/readers")
public class ReaderController {
    
    @Autowired
    private ReaderService readerService;
    
    @Operation(summary = "获取所有读者", description = "查询系统中所有的读者信息")
    @GetMapping
    public ResultDTO<List<ReaderDTO>> findAll() {
        List<Reader> readers = readerService.findAll();
        List<ReaderDTO> readerDTOs = readers.stream().map(this::convertToDTO).collect(Collectors.toList());
        return ResultDTO.success(readerDTOs);
    }
    
    @Operation(summary = "根据ID获取读者", description = "根据读者ID查询读者详情")
    @GetMapping("/{id}")
    public ResultDTO<ReaderDTO> findById(@Parameter(description = "读者ID") @PathVariable("id") String readerId) {
        Reader reader = readerService.findById(readerId);
        if (reader == null) {
            return ResultDTO.notFound("读者不存在");
        }
        return ResultDTO.success(convertToDTO(reader));
    }
    
    // 添加convertToDTO方法用于实体类转DTO
    private ReaderDTO convertToDTO(Reader reader) {
        ReaderDTO readerDTO = new ReaderDTO();
        BeanUtils.copyProperties(reader, readerDTO);
        return readerDTO;
    }
    
    
    @Operation(summary = "添加读者", description = "新增一位读者到系统")
    @PostMapping
    public boolean save(@Parameter(description = "读者信息") @RequestBody Reader reader) {
        return readerService.save(reader);
    }
    
    @Operation(summary = "更新读者", description = "更新读者的详细信息")
    @PutMapping
    public boolean update(@Parameter(description = "更新后的读者信息") @RequestBody Reader reader) {
        return readerService.update(reader);
    }
    
    @Operation(summary = "删除读者", description = "从系统中删除指定ID的读者")
    @DeleteMapping("/{id}")
    public boolean delete(@Parameter(description = "读者ID") @PathVariable("id") String readerId) {
        return readerService.delete(readerId);
    }
}